<template>
    <div class="editor-html">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        :style="{ height: height + 'px', 'overflow-y': 'hidden' }"
        :model-value="modelValue"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onChange="onChange"
        @onUpdataImage="handleUploadImage"
      />
    </div>
  </template>
  
  <script>
  import "@wangeditor/editor/dist/css/style.css"; // 引入 css
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  
  export default {
    name: 'EditorHtml',
    components: {
      Editor,
      Toolbar
    },
    props: {
      modelValue: {
        type: String,
        default: ""
      },
      height: {
        type: Number,
        default: 500
      }
    },
    data() {
      return {
        mode: "default",
        editorRef: null,
        toolbarConfig: {},
        editorConfig: {
          placeholder: "请输入内容...",
          MENU_CONF: {
            uploadImage: {
              server: "",
              customUpload: (file, insertFn) => {
                // 不上传到服务器,直接插入编辑器
                this.handleUploadImage(file, insertFn);
              }
            }
          }
        },
        imageList: []
      }
    },
    methods: {
      onChange(editor) {
        this.$emit("update:modelValue", editor.getHtml());
      },
      handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例,重要!
      },
      handleUploadImage(file, insertFn) {
        // 不上传到服务器,直接插入编辑器
        const url = URL.createObjectURL(file);
        insertFn(url, "", "");
        this.imageList.push(file);
        this.$emit('onUploadImage', this.imageList);
      }
    },
    beforeUnmount() {
      if (this.editorRef) {
        this.editorRef.destroy();
      }
    }
  }
  </script>
  
  <style lang="scss">
  .editor-html {
    border: 1px solid #ddd;
  }
  ::v-deep .w-e-text-container .w-e-text{
    font-size: 18px;
  }
  </style>